package com.yiguantong.police.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yiguantong.police.R;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.yiguantong.police.BaseActivity;
import com.yiguantong.police.LineEditText;
import com.yiguantong.police.retrofit.RetrofitUtil;
import com.yiguantong.police.ui.utils.MyLog;
import com.yiguantong.police.ui.utils.Util;
import com.yiguantong.police.webview.WebViewActivity;

import androidx.annotation.Nullable;

import java.io.IOException;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;


public class LoginActivity extends BaseActivity implements View.OnClickListener {

    private TextView btnlogin;
    private RelativeLayout loginLayout;
    private LineEditText loginTelnumberEdit;
    private LineEditText loginPassWordEdit;
    private TextView toLogin;
    private String mobile, pwd;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_activity_layout);
        initView();
        initData();
        getPermission();
    }

    private void initView() {
        loginLayout = findViewById(R.id.login_layout);
        loginTelnumberEdit = findViewById(R.id.login_telnumber_edit);
        loginPassWordEdit = findViewById(R.id.login_pass_word_edit);
        btnlogin = findViewById(R.id.login_btn);
//        loginTelnumberEdit.setText("18706409993");
//        loginPassWordEdit.setText("1234");
    }

    private void initData() {
        btnlogin.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login_btn:
                login();
                break;
        }
    }

    /**
     * 跳转授权页面
     */
    private void getPermission() {
        RxPermissions.getInstance(this).requestEach(Manifest.permission.CAMERA,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Permission>() {

                    @Override
                    public void accept(Permission permission) throws Exception {
                    }
                });

    }

    private void login() {
        //验证
        mobile = loginTelnumberEdit.getText().toString().trim();
        pwd = loginPassWordEdit.getText().toString().trim();
        if (!Util.isValidPhoneNum(mobile)) {
            return;
        }
        if (TextUtils.isEmpty(pwd)) {
            toast("密码不能为空！", true);
            return;
        }


//        RequestBody body = FormBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toJSONString());
//        Observable observable = RetrofitUtil.newApi().validateLogin(body);
//        observable.subscribeOn(Schedulers.newThread()).observeOn(Schedulers.newThread()).subscribe(new CustomObserver() {
//            @Override
//            public void onSuccess(String jsonString) {
//                MyLog.i("onSuccess:" + jsonString);
//                // todo 解析数据，跳转页面
//                String url = "";
//                loginSuccess(url);
//
//            }
//
//            @Override
//            public void onError(@NonNull Throwable e) {
//                MyLog.i("onError");
//            }
//        });
//        Map<String,String> headerMap = new HashMap<>();
//        headerMap.put("mobile", "18706409993");
//        headerMap.put("password", "1234");

        String testUrl = "http://223.99.141.143:8080/bpi/loginInfo/validateAdminLogin?mobile=" + mobile + "&password=" + pwd;
//        String testUrl = "http://47.105.154.119:8989/loginInfo/validateAdminLogin?mobile=" + mobile + "&password=" + pwd;
        Uri uri = Uri.parse(testUrl);
        String baseUrl = uri.getScheme() + "://" + uri.getHost();
        if (!baseUrl.endsWith("/")) {
            baseUrl += "/";
        }
        String pathUrl = testUrl.replace(baseUrl, "");
        RetrofitUtil.Api(baseUrl).testLogin(pathUrl)
                .subscribeOn(Schedulers.io()).observeOn(Schedulers.newThread()).subscribe(new Observer<ResponseBody>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {
                String aaa = d.toString();
                MyLog.i("aaa" + d);
                MyLog.i("onSubscribe");
            }

            @Override
            public void onNext(@NonNull ResponseBody responseBody) {
                try {
                    String response = responseBody.string();
                    MyLog.i("onNext---" + response);
                    JSONObject object = JSON.parseObject(response);
                    String success = object.getString("success");
                    String msg = object.getString("msg");
                    MyLog.i("success------" + success);
                    if ("true".equals(success)) {
                        String url = "http://223.99.141.143:8080/hewuye/index.html#/HealthReporting/adminReportMain?adminMobile=" + mobile;
//                        String url = "http://47.105.154.119:8080/hewuye/index.html#/HealthReporting/adminReportMain?adminMobile=" + mobile;
                        loginSuccess(url);
                    } else {
                        toast(msg, false);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(@NonNull Throwable e) {
                MyLog.i("onError" + e);
            }

            @Override
            public void onComplete() {
                MyLog.i("onComplete");
            }
        });

//        loginLayout.setVisibility(View.INVISIBLE);


    }

    private void loginSuccess(String url) {
        Intent intent = new Intent(this, WebViewActivity.class);
        intent.putExtra("url", url);
        startActivity(intent);
        LoginActivity.this.finish();
    }
}
